import json
import logging
import os
import threading
import time
from socket import socket, AF_INET, SOCK_STREAM


# config读取
config = json.loads(open(r'deleteConfig.json', encoding='utf-8').read())
# 消息推送
HOST = config["sendIP"]
PORT = config["sendPort"]
ADDR = (HOST, PORT)
# 监控ID
monitor = config["monitor"]
checkPath = config['checkPath']
overDay = config['overDay']


# 创建一个logger
logger = logging.getLogger('listen')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('delete.log')
fh.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)


# 监控心跳
def selfHeart():
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "heart", "monitor": monitor}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------selfHeart')
    finally:
        threading.Timer(60, selfHeart, ()).start()


# 消息推送
def sendMSG(msg):
    try:
        tcpCliSock = socket(AF_INET, SOCK_STREAM)
        tcpCliSock.connect(ADDR)
        data = {"type": "forward", "monitor": monitor, "msg": msg}
        tcpCliSock.send(str(data).encode())
        tcpCliSock.close()
    except Exception as r:
        logger.error(str(r) + '--------sendMSG')
        print('请求失败，继续请求')


# 单位换算 内存 字节->对应单位
def bytes2human(n):
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)
    return '%sB' % n


def checkFile(filePath):
    logger.info('开始遍历删除---' + filePath)
    num = 0
    size = 0.0
    for root, dirs, files in os.walk(filePath):
        for f in files:  # 遍历文件夹
            dirPath = os.path.join(root, f)  # 拼接文件名路径
            if int((time.time() - os.stat(dirPath).st_mtime)/60/60/24) > overDay:
                fileSize = os.path.getsize(dirPath)
                size = size + fileSize
                logger.info('删除了文件' + dirPath + '----' + bytes2human(fileSize))
                os.remove(dirPath)
                num = num + 1
    logger.info(filePath + '遍历删除完毕，共删除了' + str(num) + '个文件,释放空间'+bytes2human(size)+',阈值：（' + str(overDay) + '）天')
    # print('配置项' + str(filePath) + ',找到超出阈值（' + str(overDay) + '天）的文件数目共有' + str(num) + '个，已经删除,释放空间' + bytes2human(size))
    sendMSG('配置项' + str(filePath) + ',找到超出阈值（' + str(overDay) + '天）的文件数目共有' + str(num) + '个，已经删除,释放空间' + bytes2human(size))


def ergodic():
    try:
        for path in checkPath:
            checkFile(path)
    except Exception as r:
        logger.error(str(r) + '--------遍历删除出现异常')
    finally:
        threading.Timer(86400, ergodic, ()).start()


threading.Thread(target=selfHeart, ).start()
ergodic()
sendMSG('定期删除超时文件脚本启动')